package org.jeecg.glr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.glr.entity.GlrLightCurrent;
import org.jeecg.glr.entity.GlrLightData;
import org.jeecg.glr.service.IGlrLightCurrentService;
import org.jeecg.glr.service.IGlrLightDataService;
import org.jeecg.glr.service.IGlrLightTypeService;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @Description: 路灯网关统计数据
* @Author: jeecg-boot
* @Date:   2020-03-12
* @Version: V1.0
*/
@RestController
@RequestMapping("/glr/glrLightData")
@Slf4j
public class GlrLightDataController extends JeecgController<GlrLightData, IGlrLightDataService> {
   @Autowired
   private IGlrLightCurrentService glrLightCurrentService;
    @Autowired
    private IGlrLightDataService glrLightDataService;
   /**
    * 分页列表查询
    *
    * @param glrLightData
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @GetMapping(value = "/list")
   public Result<?> queryPageList(GlrLightData glrLightData,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {

       if (StringUtil.isNotEmpty(glrLightData.getDateTime())){
           String st1=glrLightData.getDateTime();
           glrLightData.setDateTime("");
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
           try {
               glrLightData.setCreateTime(sdf.parse(st1));
           } catch (ParseException e) {
               e.printStackTrace();
           }
       }
       Map<String, String[]> parameterMap=new HashMap(req.getParameterMap());
       parameterMap.remove(QueryGenerator.ORDER_COLUMN);
       parameterMap.remove(QueryGenerator.ORDER_TYPE);
       QueryWrapper<GlrLightData> queryWrapper = QueryGenerator.initQueryWrapperCode(glrLightData, req.getParameterMap());
       queryWrapper.orderByDesc("create_time");
       queryWrapper.orderByAsc("gata_way_code");
       queryWrapper.orderByAsc("lig_code");

       Page<GlrLightData> page = new Page<GlrLightData>(pageNo, pageSize);
       IPage<GlrLightData> pageList = glrLightDataService.page(page, queryWrapper);


       /*
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       Date d2  = new Date();
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(d2);
       calendar.add(calendar.DATE, -1);
       String stDate=sdf.format(calendar.getTime());
       log.info(stDate);
       stDate="2020-06-16";
       glrLightDataService.doSaveDate(stDate);
       */



       /*

       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       Date d2  = new Date();
       //计算一段时间

       Date d1 = null;
       try {
           // 注意格式需要与上面一致，不然会出现异常
           d1 = sdf.parse(" 2020-06-16");
       } catch (ParseException e) {
           e.printStackTrace();
       }

       Date tmp = d1;
       Calendar dd = Calendar.getInstance();
       dd.setTime(d1);

       // 打印2018年2月25日到2018年3月5日的日期
       while (tmp.getTime() < d2.getTime()) {
           tmp = dd.getTime();

           String stDate=sdf.format(dd.getTime());
           log.info(stDate);
           glrLightDataService.doSaveDate(stDate);
           // 天数加上1
           dd.add(Calendar.DAY_OF_MONTH, 1);
       }*/

       return Result.ok(pageList);
   }

    @RequestMapping(value = "lightReportChart")
    @ResponseBody
    public Map<String, Object> lightReportChart(String ligCode, String gatawayCode, String year,String month,int type){
        List<String> list_ym=null;
        SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
        if ("00".equals(month)){
            try {
                list_ym = DateUtils.getYearFullDay(sft.parse(year+"-01-01"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            try {
                list_ym = DateUtils.getMonthFullDay(sft.parse(year+"-"+month+"-01"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();

        List<Map<String, Object>> list = glrLightDataService.doGetPowerReportListById(ligCode, gatawayCode,year,month,type);

        List<String> dateList = new LinkedList<String>();
        List<BigDecimal> day_Electricity_List = new LinkedList<BigDecimal>();
        List<BigDecimal> economy_Electricity_List = new LinkedList<BigDecimal>();
        List<BigDecimal> avg_vol_List = new LinkedList<BigDecimal>();
        List<BigDecimal> avg_cur_List = new LinkedList<BigDecimal>();
        List<BigDecimal> avg_brightness_List = new LinkedList<BigDecimal>();
        List<BigDecimal> avg_power_List = new LinkedList<BigDecimal>();
        List<BigDecimal> avg_Temperature_List = new LinkedList<BigDecimal>();

        int index=0;
        for (String s : list_ym) {
            //if(!dateList.contains(s)){
            dateList.add(s);

            boolean bfind=false;
            for (Map<String, Object> tbLightData : list){
                if (s.equals(tbLightData.get("create_date11"))){
                    bfind=true;
                    //dateList.add(tbLightData.getDateTime());
                    day_Electricity_List.add(new BigDecimal(tbLightData.get("day_Electricity").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    economy_Electricity_List.add(new BigDecimal(tbLightData.get("economy_Electricity").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    avg_vol_List.add(new BigDecimal(tbLightData.get("avg_vol").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    avg_cur_List.add(new BigDecimal(tbLightData.get("avg_cur").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    avg_brightness_List.add(new BigDecimal(tbLightData.get("avg_brightness").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    avg_power_List.add(new BigDecimal(tbLightData.get("avg_power").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    avg_Temperature_List.add(new BigDecimal(tbLightData.get("avg_Temperature").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
            if (!bfind){
                day_Electricity_List.add(index,new BigDecimal(0));
                economy_Electricity_List.add(index,new BigDecimal(0));
                avg_vol_List.add(index,new BigDecimal(0));
                avg_cur_List.add(index,new BigDecimal(0));
                avg_brightness_List.add(index,new BigDecimal(0));
                avg_power_List.add(index,new BigDecimal(0));
                avg_Temperature_List.add(index,new BigDecimal(0));
            }
            index++;
        }

        map.put("dateList", dateList);
        map.put("day_Electricity_List", day_Electricity_List);
        map.put("economy_Electricity_List", economy_Electricity_List);
        map.put("avg_vol_List", avg_vol_List);
        map.put("avg_cur_List", avg_cur_List);
        map.put("avg_brightness_List", avg_brightness_List);
        map.put("avg_power_List", avg_power_List);
        map.put("avg_Temperature_List", avg_Temperature_List);
        return map;
    }

    @RequestMapping(value = "datagridLightReportChart")
    @ResponseBody
    public Result<?> datagridLightReportChart(String ligCode, String gataWayCode, String dateTime){

        List<Map<String, Object>> list = glrLightDataService.doGetPowerReportListById1(ligCode, gataWayCode,dateTime);

        Integer total = list.size();
        IPage page=new IPage() {
            @Override
            public List<OrderItem> orders() {
                return null;
            }

            @Override
            public List getRecords() {
                return null;
            }

            @Override
            public IPage setRecords(List records) {
                return null;
            }

            @Override
            public long getTotal() {
                return 0;
            }

            @Override
            public IPage setTotal(long total) {
                return null;
            }

            @Override
            public long getSize() {
                return 0;
            }

            @Override
            public IPage setSize(long size) {
                return null;
            }

            @Override
            public long getCurrent() {
                return 0;
            }

            @Override
            public IPage setCurrent(long current) {
                return null;
            }
        };
        page.setRecords(list);
        page.setSize(total);
        page.setCurrent(0);
        page.setPages(1);
        page.setTotal(total);

        IPage<Map<String, Object>> result = new Page<>(page.getCurrent(), page.getSize(), total);
        result.setRecords(list);

        return Result.ok(result);
    }





   /**
    *   添加
    *
    * @param glrLightData
    * @return
    */
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody GlrLightData glrLightData) {
       glrLightDataService.save(glrLightData);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param glrLightData
    * @return
    */
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody GlrLightData glrLightData) {
       glrLightDataService.updateById(glrLightData);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       glrLightDataService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.glrLightDataService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       GlrLightData glrLightData = glrLightDataService.getById(id);
       if(glrLightData==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(glrLightData);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param glrLightData
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, GlrLightData glrLightData) {
       return super.exportXls(request, glrLightData, GlrLightData.class, "路灯历史数据");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, GlrLightData.class);
   }

}
